package br.com.rapidrest.chain;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import br.com.rapidrest.exception.ChainException;
import br.com.rapidrest.util.MethodInvoker;

public class MethodInvokeCommand implements Command {

	@Override
	public void execute(Chain chain) throws ChainException {
		BasicChainContext context = (BasicChainContext) chain.getContext();
		Method method = context.getMethod();
		if (method != null) {
			String[] params = context.getRequestScope().getParams();
			MethodInvoker methodInvoker = new MethodInvoker(method);
			Object returnedValue;
			try {
				returnedValue = methodInvoker.invoke(context.getBean(), params);
			} catch (NoSuchMethodException e) {
				throw new ChainException(e);
			} catch (InstantiationException e) {
				throw new ChainException(e);
			} catch (IllegalAccessException e) {
				throw new ChainException(e);
			} catch (InvocationTargetException e) {
				throw new ChainException(e);
			}
			context.setReturnedValue(returnedValue);
		}
		chain.proceed();
	}

}
